<template>
  <el-upload
    class="avatar-uploader"
    action=""
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload"
    :http-request="uploadImage"
  >
    <img v-if="value" :src="value" class="avatar">
    <i v-else class="el-icon-plus avatar-uploader-icon" />
  </el-upload>
</template>

<script>
import COS from 'cos-js-sdk-v5'
export default {
  name: 'UploadPhoto',
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  methods: {
    handleAvatarSuccess(res, file) {
      console.log(res, file)
      const photo = URL.createObjectURL(file.raw)
      console.log(photo)
    },
    beforeAvatarUpload(file) {
      const isImg = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp'].includes(file.type)
      const isLt5M = file.size / 1024 / 1024 < 5

      if (!isImg) {
        this.$message.error('上传头像图片只能是 JPG / PNG / GIF / WEBP 格式!')
      }
      if (!isLt5M) {
        this.$message.error('上传头像图片大小不能超过 5MB!')
      }
      return (isImg && isLt5M)
    },
    uploadImage(params) {
      console.log(params.file)
      const cos = new COS({
        SecretId: 'AKIDlokWBh1EH8qOmyymQtAFAtPjrnX7Wkog',
        SecretKey: 'm2HoERTM3oTFtQpQvELI3jGcnodHl4FP'
      }) // 完成cos对象的初始化
      // cos.putObject({
      //   Bucket: 'zll241212-1310674375', // 存储桶名称
      //   Region: 'ap-guangzhou', // 地域名称
      //   Key: params.file.name, // 文件名称
      //   StorageClass: 'STANDARD', // 固定值
      //   Body: params.file // 文件对象
      // }, (err, data) => {
      //   console.log(err, data)
      //   if (data.statusCode === 200 && data.Location) {
      //     // 拿到了腾讯云返回的地址
      //     // 通过input自定义事件将地址传出去
      //     this.$emit('input', 'http://' + data.Location) // 将地址返回了
      //   } else {
      //     this.$message.error(err.message) // 上传失败提示消息
      //   }
      // })
      cos.putObject({
        Bucket: 'zll241212-1310674375',
        Region: 'ap-guangzhou',
        Key: params.file.name,
        StorageClass: 'STANDARD',
        Body: params.file
      }, (err, data) => {
        if (data && data.statusCode === 200 && data.Location) {
          this.$emit('input', 'https://' + data.Location)
        } else {
          console.warn('Unexpected response data:', data)
          this.$message.error('上传失败: ' + err.message || err)
        }
      })
    }
  }
}
</script>

<style scoped>
  .avatar-uploader .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
      border-color: #409EFF;
  }

  .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      line-height: 178px;
      text-align: center;
  }

  .avatar {
      width: 178px;
      height: 178px;
      display: block;
  }

</style>
